package com.party.admin.web.controller.coupon;

import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.coupon.Coupon;
import com.party.core.model.gift.GiftCoupon;
import com.party.core.service.coupon.ICouponCodeService;
import com.party.core.service.coupon.ICouponService;
import com.party.core.service.gift.IGiftCouponService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author：yifeng
 * @description： 券码控制器
 * @date：Created in  2017/11/27 下午 15:01
 **/
@Controller
@RequestMapping("coupon/coupon")
public class CouponController {
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponCodeService couponCodeService;
    @Autowired
    private IGiftCouponService giftCouponService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 券列表
     *
     * @param coupon
     * @param commonInput
     * @param page
     * @return
     */
    @RequestMapping("list")
    public ModelAndView couponList(Coupon coupon, CommonInput commonInput, Page page, String eStart, String eEnd) {
        ModelAndView mv = new ModelAndView("coupon/couponList");
        page.setLimit(20);
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        // 报名截止时间
        if (StringUtils.isNotEmpty(eStart)) {
            params.put("eStart", eStart);
            mv.addObject("eStart", eStart);
        }
        if (StringUtils.isNotEmpty(eEnd)) {
            params.put("eEnd", eEnd);
            mv.addObject("eEnd", eEnd);
        }
        List<Coupon> couponList = couponService.webListPage(coupon, params, page);
        for (Coupon cc : couponList) {
            Long stock = couponCodeService.getCountByCoupon(cc.getId());
            if (!cc.getStock().equals(stock)) {
                cc.setStock(stock);
                couponService.update(cc);
            }
        }

        mv.addObject("couponList", couponList);
        mv.addObject("page", page);
        mv.addObject("input", commonInput);
        return mv;
    }

    /**
     * 新增/编辑表单
     *
     * @param couponId 券id
     * @return
     */
    @RequestMapping("toForm")
    public ModelAndView toForm(String couponId) {
        ModelAndView mv = new ModelAndView("coupon/couponForm");
        if (StringUtils.isNotEmpty(couponId)) {
            Coupon coupon = couponService.get(couponId);
            mv.addObject("coupon", coupon);
        }
        return mv;
    }

    /**
     * 保存券
     *
     * @param coupon
     * @param result
     * @return
     */
    @ResponseBody
    @RequestMapping("save")
    public AjaxResult save(Coupon coupon, String startDate, String endDate, BindingResult result) {
        String memberId = RealmUtils.getCurrentUser().getId();
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        try {
            if (StringUtils.isNotEmpty(startDate)) {
                Date startTime = DateUtils.parse(startDate, "yyyy-MM-dd");
                coupon.setStartTime(startTime);
            }
            if (StringUtils.isNotEmpty(endDate)) {
                Date endTime = DateUtils.parse(endDate, "yyyy-MM-dd");
                coupon.setEndTime(endTime);
            }
            if (StringUtils.isEmpty(coupon.getId())) {
                coupon.setCreateBy(memberId);
                coupon.setUpdateBy(memberId);
                couponService.insert(coupon);
            } else {
                coupon.setUpdateBy(memberId);
                couponService.update(coupon);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存票券异常", e);
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 删除券码
     *
     * @param couponId 券id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult delete(String couponId) {
        if (StringUtils.isEmpty(couponId)) {
            return AjaxResult.error("主键不能为空");
        }
        try {
            List<GiftCoupon> coupons = giftCouponService.findByCouponId(couponId);
            if (coupons.size() > 0) {
                return AjaxResult.error("该票券已分配给礼包，不能删除");
            } else {
                Long couponCodeCount = couponCodeService.getCountByCoupon(couponId);
                if (couponCodeCount > 0) {
                    return AjaxResult.error("该票券下已有核销码，不能删除");
                }
            }
            couponService.delete(couponId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除票券异常", e);
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 选择券
     *
     * @param query
     * @param page
     * @return
     */
    @RequestMapping("selectCoupon")
    public ModelAndView selectCoupon(Coupon query, Page page, String couponId, String giftId) {
        ModelAndView mv = new ModelAndView("coupon/selectCoupon");
        List<Coupon> coupons = couponService.listPage(query, page);
        for (Coupon c : coupons) {
            long notAllotNum = c.getStock() - c.getAllotNum(); // 剩余未分配的券
            c.setAllotNum(notAllotNum);
        }
        mv.addObject("coupons", coupons);
        mv.addObject("page", page);
        mv.addObject("coupon", query);

        if (StringUtils.isNotEmpty(couponId) && StringUtils.isNotEmpty(giftId)) {
            GiftCoupon coupon = giftCouponService.getUnique(new GiftCoupon(giftId, couponId));
            mv.addObject("selectCoupon", coupon);
        }
        return mv;
    }
}
